<?php
require_once("../includes/Response.php");
$uploaddir = "Users/zhangfulong/Sites/ECShop/images/dober/";//设置文件保存目录
$type = array("jpg", "gif", "bmp", "jpeg", "png");//设置允许上传文件的类型

//获取文件后缀名函数
function fileext($filename)
{
    return substr(strrchr($filename, '.'), 1);
}

//生成随机文件名函数
function random($length)
{
    $hash = 'CR-';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;
    mt_srand((double)microtime() * 1000000);
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

$a = strtolower(fileext($_FILES['user_pic']['name']));
//判断文件类型
if (!in_array($a, $type)) {
    $text = implode(",", $type);
    echo "您只能上传以下类型文件: ", $text, "<br>";
    return Response::json(410, "您只能上传" . $text . "类型的文件", $filename);
} //生成目标文件的文件名
else {
    $filename = explode(".", $_FILES['user_pic']['name']);
    do {
        $filename[0] = random(10); //设置随机数长度
        $name = implode(".", $filename);
        $uploadfile = $uploaddir . $name;
    } while (file_exists($uploadfile));

    if (move_uploaded_file($_FILES['user_pic']['tmp_name'], $uploadfile)) {
        if (is_uploaded_file($_FILES['user_pic']['tmp_name'])) {

            echo "上传失败!";
            return Response::json(407, "上传失败", $uploadfile);
        }else{
            echo  "上传成功";
        }
    }

}
?>